﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AppPressFramework;
using ApplicationClasses;

namespace Application
{

    public partial class AppLogic
    {
        private static string CreateRandomPassword(int passwordLength)
        {
            string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";
            char[] chars = new char[passwordLength];
            Random rd = new Random();

            for (int i = 0; i < passwordLength; i++)
            {
                chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
            }

            return new string(chars);
        }
        public static void OnClick(AppPress a, UserManagementClass.ChangePasswordFieldClass ChangePassword)
        {
            ChangePasswordClass.Popup(a, ChangePassword.FormData.UserManagement.GetSingleSelection().id, null);
        }
        public static void OnClick(AppPress a, UserManagementClass.UserManagementPopupClass.SaveUserManagementFieldClass SaveUserManagement)
        {
            // for new User create a random Password
            var UserManagement = SaveUserManagement.FormData;

            var newUser = UserManagement.IsNew;
            UserManagement.Save(a);
            if (newUser)
            {
                var pwd = CreateRandomPassword(6);
                a.ExecuteNonQuery("Update Application_Users Set Password=HASHBYTES('SHA1','" + pwd + "') Where Id=" + UserManagement.id);
                a.AlertMessage("New user has been created with Password: " + pwd);
            }
            UserManagement.RefreshContainer(a);
            a.ClosePopup();
        }

    }
}